import numpy as np
from PIL import ImageFont
from relic import Relic
import re

font_18 = ImageFont.truetype("../font.ttf", size=18)
font_20 = ImageFont.truetype("../font.ttf", size=20)
font_28 = ImageFont.truetype("../font.ttf", size=28)
font_35 = ImageFont.truetype("../font.ttf", size=35)


# type0是数据标注里面的类别
def get_one_box_train_y(xy, bbox, x1y1=None, bbox1=None, type0: int = 0) -> str:
    # 左上角坐标与右下角坐标
    x0 = 0
    y0 = 0
    x1 = 0
    y1 = 0
    # 比较，取最左最上的两个为左上角坐标，最右最下的两个数值为右下角坐标
    if bbox1 is not None and x1y1 is not None:
        x0 = np.min([xy[0] + bbox[0], x1y1[0] + bbox1[0]])
        y0 = np.min([xy[1] + bbox[1], x1y1[1] + bbox1[1]])
        x1 = np.max([xy[0] + bbox[2], x1y1[0] + bbox1[2]])
        y1 = np.max([xy[1] + bbox[3], x1y1[1] + bbox1[3]])
    else:
        x0 = xy[0] + bbox[0]
        y0 = xy[1] + bbox[1]
        x1 = xy[0] + bbox[2]
        y1 = xy[1] + bbox[3]

    # stra = "" + str(list(Relic.names.keys())[list(Relic.names.values()).index(text)])
    # 生成数据标注文本
    stra = str(type0)
    stra += " " + str(((x0 + x1) / 2.0) / 410.0)
    stra += " " + str(((y0 + y1) / 2.0) / 460.0)
    stra += " " + str((x1 - x0 + 1) / 410.0)
    stra += " " + str((y1 - y0 + 1) / 460.0)

    return stra


def generate_relic_box_text(relic: Relic):
    box_text = []

    # 圣遗物类型标注
    box_text.append(get_one_box_train_y(xy=(24, 57), bbox=font_18.getbbox(relic.relic_type), type0=0))

    # 圣遗物主词条加数值标注
    box_text.append(get_one_box_train_y(xy=(24, 125),
                                        x1y1=(24, 147),
                                        bbox=font_18.getbbox(relic.main_entry_type),
                                        bbox1=font_35.getbbox(
                                            text=re.findall(r'\d+\.\d+%|\d+%|\d+\.\d+|\d+',
                                                            relic.main_entry_str)[0]),
                                        type0=1))

    y_pointer = 299
    # 副词条数值加列表的标注
    for i in range(len(relic.secondary_lemma_str)):
        # box_text.append(get_one_box_train_y(xy=(44, 236 + y_pointer),
        box_text.append(get_one_box_train_y(xy=(44, y_pointer),
                                            bbox=font_20.getbbox(relic.secondary_lemma_str[i]),
                                            type0=2))
        y_pointer += 32

    # 圣遗物套装标注
    box_text.append(get_one_box_train_y(xy=(24, y_pointer),
                                        bbox=font_20.getbbox(relic.coordinate_name),
                                        type0=3))

    # 判断是否加锁
    # 4unlock 5lock
    lock = 4
    if relic.locked:
        lock = 5
    box_text.append(get_one_box_train_y(xy=(353, 249),
                                        bbox=(0, 0, 37, 37), type0=lock))

    return box_text
